//
//  UIButton+Extension.swift
//  weibo
//
//  Created by yellow on 15/10/14.
//  Copyright © 2015年 yellow. All rights reserved.
//

import UIKit

extension UIButton{
    /// UIButton分类，根据图片名称和背景图片名称创建按钮，按钮大小根据图片大小决定
    ///
    /// - parameter imageName:     图片名称
    /// - parameter backImageName: 背景图片名称(可选)
    ///
    /// - returns: 自定义按钮
    convenience init(imageName:String,backImageName:String?){
        //当调用父类init后，修改btn的图片，背景图片的normal，higthlight
        self.init()
        setImage(UIImage(named: imageName), forState: UIControlState.Normal)
        setImage(UIImage(named: imageName+"_highlighted"), forState: UIControlState.Highlighted)
        
        //使用 imageName 创建图像时，如果 imageName == ""，会报 CUICatalog: Invalid asset name supplied: 错误
        if let backImageName = backImageName{
            setBackgroundImage(UIImage(named: backImageName), forState: .Normal)
            setBackgroundImage(UIImage(named: backImageName+"_highlighted"), forState: .Highlighted)
        }
        sizeToFit()
    }
    
    /// UIButton分类，设置按钮显示的名称，背景图片名称以及触发的点击事件
    ///
    /// - parameter title:      按钮显示的名称
    /// - parameter color:      按钮显示的文字的渲染色
    /// - parameter imageName:  背景图片名称
    /// - parameter actionName: 触发的点击事件
    ///
    /// - returns: UIButton
    convenience init(title:String,color:UIColor,imageName:String,actionName:Selector,target:AnyObject){
        self.init()
        setBackgroundImage(UIImage(named:imageName), forState:UIControlState.Normal)
        setTitle(title, forState: UIControlState.Normal)
        setTitleColor(color, forState: .Normal)
        addTarget(target, action: actionName, forControlEvents: UIControlEvents.TouchUpInside)
        sizeToFit()
    }
    
    /// 设置左图右文字的按钮
    /// - returns: UIButton
    convenience init(title:String,color:UIColor,leftImageName:String,fontSize:CGFloat){
        self.init()
        setTitle(title, forState: UIControlState.Normal)
        titleLabel?.font = UIFont.systemFontOfSize(fontSize)
        setTitleColor(color, forState: UIControlState.Normal)
        setImage(UIImage(named: leftImageName), forState: UIControlState.Normal)
    }
}